<?php
/*
 * Created on Apr 2, 2009
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

class Gallery_AjaxController extends Clu_Controller_Action_Hvn
{
	public function init()
	{
//		require (APP_PATH."/library/Utils/Utils_Image.php");
		$this->m = new gallery_Model_Gallery();
	}

	public function processUploadedFileAction()
	{
//		if (empty($_FILES))
//		{
//  			die("0");
//		}
		$galleryId = $_REQUEST['folder']; /* this stupid name is becuase of uploadify*/
		//get the gallery info here to get the poster_id 
		//to get the path
		//require_once(APP_PATH . "/modules/node/Model/NodeService.php");
		$nService = new node_Model_NodeService();
		$nodeTypeInfo = $nService->getNodeTypeInfo("gallery");
		$ret = $nService->findNodeByPrimary($nodeTypeInfo, $galleryId);
		if ($ret)
			$gallery = $ret;
		else
			exit();			
		$posterId = $gallery['poster_id'];

		$ustoreDir = APP_PATH."/public/ustore/$posterId/images/original/gallery/$galleryId/";
		if (!file_exists($ustoreDir))
			mkdir($ustoreDir, 0777  , true);
		
		$ufilesDir = APP_PATH."/public/ufiles/$posterId/images/original/gallery/$galleryId/" ;
		if (!file_exists($ufilesDir))
			mkdir($ufilesDir, 0777  , true);
		
		$fileName = $_FILES['Filedata']['name'];
		//make sure the file name is unique
		$targetFile = $ustoreDir . $fileName;
		$i = 1;
		while(file_exists($targetFile))
		{
			$fileName = $i . "_" . $_FILES['Filedata']['name'];
			$targetFile = $ustoreDir . $fileName;	
			$i++;
		}
		
		//TODO: get this in
//		$IsImageValidateor = new Clu_Validate_File_IsImage ();
//		$isImage = $IsImageValidateor->isValid($_FILES['Filedata']['tmp_name'], $_FILES['Filedata']);
//		if (!$isImage)
//			exit();
		
		move_uploaded_file($_FILES['Filedata']['tmp_name'],$targetFile);
		//require_once APP_PATH."/library/common.php";
		$watermarkDir = APP_PATH."/public/watermark/";
		
		// now generate copies
		//TODO: if editors, then do watermark
		$ret = generate_image_copies ("ustore", $ustoreDir,$fileName, $watermarkDir, null, null, $posterId, false); //with wm		
		if ($ret == false)
		{
			//remove the uploaded files
			unlink ($targetFile);
			exit();
		}
		//else : update the gallery  file info
		$this->m->updateGalleryImageList($gallery, $targetFile);
		die("done"); //for the jquery.uploadify.js
//		ob_start();
//		var_dump($_FILES['Filedata']);
//		$out1 = ob_get_contents();
//		ob_end_clean();
	}
	
	public function updateThumbAction()
	{
		$galleryId = $this->_request->getParam('id');
		$thumb = $this->_request->getParam('thumb');
		//get the gallery info here to get the poster_id 
		//to get the path
		//require_once(APP_PATH . "/modules/node/Model/NodeService.php");
		$nService = new node_Model_NodeService();
		$nodeTypeInfo = $nService->getNodeTypeInfo("gallery");
		$gallery = $nService->findNodeByPrimary($nodeTypeInfo, $galleryId);
		if (!$gallery)
			$this->sendJsonError(null, "gallery not found");
		$gallery['thumb'] = $thumb;
		try 
		{
			$gallery->save();
			$ret = array ("success" => true);
			
			$this->_helper->json->sendJson($ret); 
			exit();
		} 
		catch (Exception $e)
		{
			$ret = array ("success" => false, "errorMessage" => $e->getMessage());
			$this->_helper->json->sendJson($ret);
			exit();
		}
	}
	
	public function updateImageTitleAction()
	{
		$galleryId = $this->_request->getParam('id');
		$filename = $this->_request->getParam('filename');
		$title =  $this->_request->getParam('title');
		
		//get the gallery info here to get the poster_id 
		//to get the path
		//require_once(APP_PATH . "/modules/node/Model/NodeService.php");
		$nService = new node_Model_NodeService();
		$nodeTypeInfo = $nService->getNodeTypeInfo("gallery");
		$gallery = $nService->findNodeByPrimary($nodeTypeInfo, $galleryId);
		if (!$gallery)
			$this->sendJsonError(null, "gallery not found");
		
		$ret = $this->m->updateGalleryImageTitle($gallery, $filename, $title);
		$this->_helper->json->sendJson($ret);
		
	}
	
	/* TODO: Check permission here */
	public function deleteImageAction()
	{
		$galleryId = $this->_request->getParam('id');
		$filename = $this->_request->getParam('filename');
		
		//get the gallery info here to get the poster_id 
		//to get the path
		//require_once(APP_PATH . "/modules/node/Model/NodeService.php");
		$nService = new node_Model_NodeService();
		$nodeTypeInfo = $nService->getNodeTypeInfo("gallery");
		$gallery = $nService->findNodeByPrimary($nodeTypeInfo, $galleryId);
		if (!$gallery)
			$this->sendJsonError(null, "gallery not found");

		$sess = new Zend_Session_Namespace(CLU_NS);
		if ($gallery->poster_id != $sess->userId && 
				false === strpos($sess->userPermissions, 'update gallery'))
			$this->_helper->json->sendJson(array("success" => false, 
											"errorMessage" => __("You are not allowed to delete images from this gallery")));
		
		$ret = $this->m->deleteGalleryImage($gallery, $filename);
		$this->_helper->json->sendJson($ret);
	}

	/*
	 * Used for adding gallery for place, event, node(news) types of content
	 * This is not used for adding personal gallery, which probably every user should
	 * have the right
	 */
	public function addGalleryAction()
	{
		$sess = new Zend_Session_Namespace(CLU_NS);
		$contentType = $this->_request->getParam('content_type');
		$contentId = $this->_request->getParam('content_id');
		if ($contentType == "place")
		{
			//require_once(APP_PATH . "/modules/place/Model/Place.php");
			$model = new place_Model_Place();
			$row = $model->findByPrimary($contentId);
		}
		else if ($contentType == "event")
		{
			//require_once(APP_PATH . "/modules/event/Model/Event.php");
			$model = new event_Model_Service();
			$row = $model->findByPrimary($contentId);
		}
		else if ($contentType == "node")
		{
			//get nodeType here as well
			$nodeType = $this->_request->getParam('node_type');
			//$this->_helper->json->sendJson(array('type' => $nodeType));
			//require_once(APP_PATH . "/modules/node/Model/NodeService.php");
			$model = new node_Model_NodeService();
			$nodeTypeInfo = $model->getNodeTypeInfo($nodeType);
			$row = $model->findNodeByPrimary($nodeTypeInfo, $contentId);
		}
		else if ($contentType == "project")
		{
			$model = new archin_Model_Service();
			$row = $model->find("project", $contentId); 
		}
		
		if (is_null($row))
			$this->_helper->json->sendJson(array("success" => false, 
											"errorMessage" => __("Could not find content")));
		else
		{
			if ($row->gallery) //gallery already exists
				$this->_helper->json->sendJson(array("success" => false, 
											"errorMessage" => __("One gallery already exists")));
			// check for permission
			if ($row->poster_id != $sess->userId && 
				false === strpos($sess->userPermissions, 'update place'))
				$this->_helper->json->sendJson(array("success" => false, 
											"errorMessage" => __("You are not allowed to create a gallery for this content")));

	        if (!$sess->userId)
	           $this->_helper->json->sendJson(array("success" => false, 
											"errorMessage" => __("Not yet logged in"))); 
			else
			{
				try
				{
					$db = Zend_Db_Table::getDefaultAdapter() ;
					//create a new gallery
			    	$c['poster_id'] = $sess->userId;
			    	$c['type'] = $contentType; 
			    	$c['created'] = time();
			    	$c['language'] = get_language_index($sess->viewLang);
				    if ($contentType == "place")
				    	$c['title'] = $row->name;
				    if ($contentType == "project")
				    	$c['title'] = $row->name_vi;
				    else
				    	$c['title'] = $row->title;
				    $c['status'] = 0; //published
				    
				    $metadata = array("poster_name" => $sess->userName);
				    $images = array();
					$c['metadata'] = serialize($metadata);
					$c['images'] = serialize($images);
				    //die_a($c);
					$db->insert("galleries", $c);
				    //attach it to the $row
					$galleryId = $db->lastInsertId();
			    	$row->gallery = $galleryId;
			    	$row->save();
			    	
			    	$this->_helper->json->sendJson(array("success" => true, 
											"galleryId" => $galleryId));
				}
				catch (Exception $e)
				{
					$this->_helper->json->sendJson(array("success" => false,
											"errorMessage" => $e->getMessage())); 
				}
			}
			
		}
	}
}
?>